package com.wwdx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

/**
 * AES对称加密工具类
 * @author liguoliang
 */
public class AesUtil {

    private static Logger logger = LoggerFactory.getLogger(AesUtil.class);

    /**
     * AES加密
     * @param str 需要加密的数据
     * @param aesKey 秘钥
     * @return 加密结果
     */
    public static String encryptStrWithAes(String str, String aesKey) {
        try {
            Cipher cipher = getCipher(Cipher.ENCRYPT_MODE,aesKey);
            byte[] encrypted = cipher.doFinal(str.getBytes(Charset.forName(ConstantHolder.Constant.UTF8)));
            return ConstantHolder.ENCODER.encodeToString(encrypted);
        } catch (Exception e) {
            logger.error("错误信息：{}",e.getMessage());
           return null;
        }
    }

    private static Cipher getCipher(int model,String aesKey) throws Exception{
        byte[] raw = aesKey.getBytes();
        SecretKeySpec key = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(model, key);
        return cipher;
    }

    /**
     * AES解密
     * @param str 需要解密的数据
     * @param aesKey 秘钥
     * @return 解密结果
     */
    public static String decryptStrWithAes(String str,String aesKey) {
        try {
            Cipher cipher = getCipher(Cipher.DECRYPT_MODE,aesKey);
            byte[] decrypted = cipher.doFinal(ConstantHolder.DECODER.decode(str));
            return new String(decrypted, Charset.forName(ConstantHolder.Constant.UTF8));
        }catch (Exception e){
            logger.error("错误信息：{}",e.getMessage());
            return null;
        }
    }
}